package kalambury.srv.web;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kalambury.KalamburyUtils;
import kalambury.db.UserEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

public class UserController extends AbstractWizardFormController{

    public UserController(){
        setCommandName("userForm");
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request)
            throws Exception {

        return new UserEntity();
    }

    @Override
    protected ModelAndView processFinish(HttpServletRequest request,
                                         HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        UserEntity user = (UserEntity)command;
        user.setPassword(KalamburyUtils.getHash(user.getPassword()));
        saveUserToDb(user);

        return new ModelAndView("ResultForm", "user", user);
    }

    @Override
    protected ModelAndView processCancel(HttpServletRequest request,
                                         HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        return new ModelAndView("WelcomePage");
    }

    @Override
    protected void validatePage(Object command, Errors errors, int page) {

        UserValidator validator = (UserValidator) getValidator();

        switch (page) {
            case 0:
                validator.validatePage1Form(command, errors);
                break;
            case 1:
                validator.validatePage2Form(command, errors);
                break;
        }
    }

    private void saveUserToDb(UserEntity newUser) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("NewPersistenceUnit");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

        em.persist(newUser);
        em.flush();

        em.getTransaction().commit();

        em.close();
        emf.close();
    }
}